﻿// <copyright file="NeighbourImporter.cs" company="Gravity Age Studios">
// Code released under the MIT license (see License.txt).
// </copyright>
// <author>Vicente Cartas Espinel</author>
// <email>vicente.cartas@gmail.com</email>
namespace LightSwitchApplication.Import
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Microsoft.LightSwitch.Framework;
    using Microsoft.LightSwitch.Framework.Client;

    internal class NeighbourImporter
    {
        private readonly int Province = 0;
        private readonly int Neighbours = 1;

        private DataWorkspace workspace;

        public NeighbourImporter(DataWorkspace workspace)
        {
            this.workspace = workspace;
        }

        public void ImportData(Stream stream, VisualCollection<BaseProvince> collection)
        {
            this.workspace.Details.Dispatcher.BeginInvoke(() =>
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string[] stringHeaders = reader.ReadLine().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    var headers = this.MapHeaders(stringHeaders);

                    int rowLength = stringHeaders.Length;
                    string[] data = reader.ReadToEnd().Split(new string[] { ";", Environment.NewLine }, StringSplitOptions.None);

                    try
                    {
                        this.SetNeighbours(collection, rowLength, headers, data);
                    }
                    catch (Exception)
                    {
                    }
                }
            });
        }

        public void ImportData(Stream stream, bool useDispatcher = true)
        {
            if (useDispatcher)
            {
                this.workspace.Details.Dispatcher.BeginInvoke(() =>
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string[] stringHeaders = reader.ReadLine().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        var headers = this.MapHeaders(stringHeaders);

                        int rowLength = stringHeaders.Length;
                        string[] data = reader.ReadToEnd().Split(new string[] { ";", Environment.NewLine }, StringSplitOptions.None);

                        try
                        {
                            var provinces = this.workspace.ApplicationData.BaseProvinces.GetQuery().Execute();
                            this.SetNeighbours(provinces, rowLength, headers, data);
                        }
                        catch (Exception)
                        {
                        }
                    }
                });
            }
            else
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string[] stringHeaders = reader.ReadLine().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    var headers = this.MapHeaders(stringHeaders);

                    int rowLength = stringHeaders.Length;
                    string[] data = reader.ReadToEnd().Split(new string[] { ";", Environment.NewLine }, StringSplitOptions.None);

                    try
                    {
                        var provinces = this.workspace.ApplicationData.BaseProvinces.GetQuery().Execute();
                        this.SetNeighbours(provinces, rowLength, headers, data);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }

        protected int?[] MapHeaders(string[] stringHeaders)
        {
            int?[] headers = new int?[2];

            for (int i = 0; i < stringHeaders.Length; i++)
            {
                if (stringHeaders[i].StartsWith("Pro", StringComparison.InvariantCultureIgnoreCase))
                {
                    headers[Province] = i;
                }
                else if (stringHeaders[i].StartsWith("Nei", StringComparison.InvariantCultureIgnoreCase))
                {
                    headers[Neighbours] = i;
                }
            }

            return headers;
        }

        private void SetNeighbours(IEnumerable<BaseProvince> collection, int rowLength, int?[] headers, string[] data)
        {
            for (int i = 0; i < data.Length - 1; i += rowLength)
            {
                if (headers[Province].HasValue)
                {
                    var startProvince = collection
                        .Where(
                            e =>
                            e.Name.Equals(data[i + headers[Province].Value].Trim(),
                                          StringComparison.InvariantCultureIgnoreCase))
                        .FirstOrDefault();

                    if (startProvince != null && headers[Neighbours].HasValue)
                    {
                        string[] neighbours = data[i + headers[Neighbours].Value].Split(new string[] { "|", ",", "/" },
                                                                                        StringSplitOptions.RemoveEmptyEntries);
                        foreach (var neighbour in neighbours)
                        {
                            var endProvince = collection
                                .Where(
                                    e => e.Name.Equals(neighbour.Trim(), StringComparison.InvariantCultureIgnoreCase))
                                .FirstOrDefault();

                            if (endProvince != null)
                            {
                                var relation = startProvince.Neighbours.AddNew();
                                relation.StartProvince = startProvince;
                                relation.EndProvince = endProvince;
                            }
                        }
                    }
                }
            }
        }
    }
}
